package com.ys.peony.car300.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.YSConstant;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.car300.CarDataManager;
import com.ys.peony.model.domain.CarModel;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import com.yklab.library.refreshlayout.adapters.CommonRecyclerViewAdapter;
import com.yklab.library.refreshlayout.holder.CommonRecyclerViewHolder;
import com.yklab.library.refreshlayout.inter.OnClickCommonListener;

public class ChoiceCarTypeActivity extends BaseActivity {

    public final static String CONFIG_TYPE = "标配";
    public final static String RESULT_POSITION = "position";
    private final static String SPECIAL_TYPE = "以上配置均无";
    private final static int TYPE_CLICK_CONFIG = 1;
    private final static int TYPE_CLICK_CARTYPE = 2;
    private final static int TYPE_CLICK_CONFIG_SPECIAL = 3;

    @BindView(R.id.recyclerview1)
    RecyclerView recyclerView1;
    @BindView(R.id.recyclerview2)
    RecyclerView recyclerView2;

    private CommonRecyclerViewAdapter mAdapter1;
    private CommonRecyclerViewAdapter mAdapter2;

    private GridLayoutManager gridLayoutManager;
    private LinearLayoutManager linearLayoutManager;

    private List<Config> list1;
    private List<CarModel.ModelInfoBean> list2;

    private List<Config> mCurCarTypeList = new ArrayList<>();

    private int mCurSelectCarTypeItem = YSConstant.INVALID;
    private int mCurClick = YSConstant.INVALID;
    private Object lock = new Object();

    @Override
    protected int getContentResId() {
        return R.layout.activity_choice_car_type;
    }

    @Override
    protected void initView() {
        list1 = new ArrayList<>();
        list2 = new ArrayList<>();
        initListener();
        initData();
    }

    private void initData() {
        CarModel carModel = CarDataManager.getInstance().getCarVinModel();
        if (carModel != null) {
            try {
                initConfigList(carModel.getModelInfo().get(0).getDiff_params());
                initCarTypeList(carModel.getModelInfo().size());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            list2.clear();
            list2.addAll(carModel.getModelInfo());
            mAdapter1.notifyDataSetChanged();
            mAdapter2.notifyDataSetChanged();
        }
    }

    private void initCarTypeList(int size) {
        mCurCarTypeList.clear();
        for (int i = 0; i < size; i++) {
            Config config = new Config();
            config.setFlag(false);
            mCurCarTypeList.add(config);
        }
    }

    private void initConfigList(CarModel.ModelInfoBean.DiffParamsBean diffParamsBean) throws IllegalAccessException {
        list1.clear();
        if (diffParamsBean != null) {
            CarModel.ModelInfoBean.DiffParamsBean.StandardGroupBean standardGroupBean = diffParamsBean.getStandard_group();
            if (standardGroupBean != null) {
                Field[] fields = standardGroupBean.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].isSynthetic() || "serialVersionUID".equals(fields[i].getName())) {
                        continue;
                    }
                    Config config = new Config();
                    config.setKey(fields[i].getName());
                    config.setValue(String.valueOf(fields[i].get(standardGroupBean)));
                    list1.add(config);
                }
            }
        }
        Config config = new Config();
        config.setKey(SPECIAL_TYPE);
        config.setValue("无");
        list1.add(config);
        list1.get(list1.size() - 1).setFlag(true);
        mCurClick = TYPE_CLICK_CONFIG_SPECIAL;
    }

    //判断该车型是否有有选中的所有配置项
    private Boolean checkConfig(CarModel.ModelInfoBean.DiffParamsBean.StandardGroupBean standardGroupBean) {
        try {
            boolean success = true;
            int temp = 0;
            for (int t = 0; t < list1.size(); t++) {
                if (list1.get(t).getFlag()) {
                    temp = 1;
                    String conf = list1.get(t).getKey();
                    if (standardGroupBean != null) {
                        Field[] fields = standardGroupBean.getClass().getDeclaredFields();
                        for (int i = 0; i < fields.length; i++) {
                            if (fields[i].isSynthetic() || "serialVersionUID".equals(fields[i].getName())) {
                                continue;
                            }
                            if (conf.equals(fields[i].getName()) && !CONFIG_TYPE.equals(String.valueOf(fields[i].get(standardGroupBean)))) {
                                success = false;
                            }
                        }
                    } else {
                        success = false;
                    }
                }
            }
            if (temp == 0) {
                success = false;
            }
            return success;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return false;
        }
    }

    private Boolean checkSpecialCarType(CarModel.ModelInfoBean.DiffParamsBean.StandardGroupBean standardGroupBean) {
        Boolean success = true;
        try {
            if (standardGroupBean != null) {
                Field[] fields = standardGroupBean.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].isSynthetic() || "serialVersionUID".equals(fields[i].getName())) {
                        continue;
                    }
                    if (CONFIG_TYPE.equals(String.valueOf(fields[i].get(standardGroupBean)))) {
                        success = false;
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return success;
        }
        return success;
    }

    //判断选中车型的配置项
    private Boolean checkCarType(String key, CarModel.ModelInfoBean.DiffParamsBean.StandardGroupBean standardGroupBean) {
        try {
            if (standardGroupBean != null) {
                Field[] fields = standardGroupBean.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if (fields[i].isSynthetic() || "serialVersionUID".equals(fields[i].getName())) {
                        continue;
                    }
                    if (key == SPECIAL_TYPE) {
                        if (CONFIG_TYPE.equals(String.valueOf(fields[i].get(standardGroupBean)))) {
                            return true;
                        }
                    } else {
                        if (key.equals(fields[i].getName())) {
                            if (CONFIG_TYPE.equals(String.valueOf(fields[i].get(standardGroupBean)))) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    private void initListener() {
        gridLayoutManager = new GridLayoutManager(getApplicationContext(), 4);
        linearLayoutManager = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        mAdapter1 = new CommonRecyclerViewAdapter(this, list1, R.layout.view_item_config) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                if (list1 == null || list1.size() < 1) {
                    return;
                }
                TextView view = ((CommonRecyclerViewHolder) holder).getView(R.id.text);
                view.setText(list1.get(position).getKey());
                ((CommonRecyclerViewHolder) holder).setViewListener(R.id.text);
                if (mCurClick == TYPE_CLICK_CARTYPE) {
                    if (YSConstant.INVALID != mCurSelectCarTypeItem) {
                        CarModel.ModelInfoBean.DiffParamsBean diffParamsBean = list2.get(mCurSelectCarTypeItem).getDiff_params();
                        if (position == list1.size() - 1) {
                            if (diffParamsBean == null || diffParamsBean.getStandard_group() == null || checkSpecialCarType(diffParamsBean.getStandard_group())) {
                                list1.get(position).setFlag(true);
                            } else {
                                list1.get(position).setFlag(false);
                            }
                        } else {
                            if (mCurSelectCarTypeItem != YSConstant.INVALID && diffParamsBean != null && checkCarType(list1.get(position).getKey(), diffParamsBean.getStandard_group())) {
                                list1.get(position).setFlag(true);
                            } else {
                                list1.get(position).setFlag(false);
                            }
                        }
                    }
                }
                if (list1.get(position).getFlag()) {
                    view.setFocusable(true);
                    view.setBackgroundResource(R.drawable.view_item_config_after);
                    view.setTextColor(getResources().getColor(R.color.white));

                } else {
                    view.setFocusable(false);
                    view.setBackgroundResource(R.drawable.view_item_config_before);
                    view.setTextColor(getResources().getColor(R.color.color_666666));
                }
            }
        };

        mAdapter1.setOnClickListener(new OnClickCommonListener() {
            @Override
            public void onClickListener(View view, int position) {
                switch (view.getId()) {
                    case R.id.text:
                        synchronized (lock) {
                            if (position < 0) {
                                return;
                            }
                            mCurSelectCarTypeItem = YSConstant.INVALID;
                            if (position == list1.size() - 1) {
                                if (view.isFocusable()) {
                                    return;
                                }
                                mCurClick = TYPE_CLICK_CONFIG_SPECIAL;
                                for (int i = 0; i < list1.size(); i++) {
                                    if (i != position) {
                                        list1.get(i).setFlag(false);
                                    }
                                }
                            } else {
                                mCurClick = TYPE_CLICK_CONFIG;
                            }
                            if (view.hasFocusable()) {
                                view.setFocusable(false);
                                list1.get(position).setFlag(false);
                            } else {
                                view.setFocusable(true);
                                list1.get(position).setFlag(true);
                            }
                            boolean temp = true;
                            for (int i = 0; i < list1.size() - 1; i++) {
                                if (list1.get(i).getFlag()) {
                                    temp = false;
                                }
                            }
                            if (temp) {
                                list1.get(list1.size() - 1).setFlag(true);
                                mCurClick = TYPE_CLICK_CONFIG_SPECIAL;
                            } else {
                                list1.get(list1.size() - 1).setFlag(false);
                            }
                            mAdapter1.notifyDataSetChanged();
                            mAdapter2.notifyDataSetChanged();
                        }
                        break;
                }
            }
        });

        mAdapter2 = new CommonRecyclerViewAdapter(this, list2, R.layout.view_item_cartype) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
                CarModel.ModelInfoBean modelInfoBean = list2.get(position);
                if (modelInfoBean == null) {
                    return;
                }
                ((CommonRecyclerViewHolder) holder).setText(R.id.content, modelInfoBean.getModel_name());
                ((CommonRecyclerViewHolder) holder).setViewListener(R.id.content);
                View view = ((CommonRecyclerViewHolder) holder).getView(R.id.content);
                if (mCurClick == TYPE_CLICK_CARTYPE) {
                    if (mCurCarTypeList.get(position).getFlag()) {
                        view.setBackgroundResource(R.drawable.view_item_cartype_after);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_EB3131));
                        view.setFocusable(true);
                        mCurCarTypeList.get(position).setFlag(false);
                    } else {
                        view.setBackgroundResource(R.drawable.view_item_cartype_before);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_666666));
                        view.setFocusable(false);
                    }
                } else if (mCurClick == TYPE_CLICK_CONFIG) {
                    CarModel.ModelInfoBean.DiffParamsBean diffParamsBean = list2.get(position).getDiff_params();
                    if (diffParamsBean != null && checkConfig(diffParamsBean.getStandard_group())) {
                        view.setBackgroundResource(R.drawable.view_item_cartype_after);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_EB3131));
                        view.setFocusable(true);
                    } else {
                        view.setBackgroundResource(R.drawable.view_item_cartype_before);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_666666));
                        view.setFocusable(false);
                    }
                } else if (mCurClick == TYPE_CLICK_CONFIG_SPECIAL) {
                    CarModel.ModelInfoBean.DiffParamsBean diffParamsBean = list2.get(position).getDiff_params();
                    if (diffParamsBean == null || diffParamsBean.getStandard_group() == null || checkSpecialCarType(diffParamsBean.getStandard_group())) {
                        view.setBackgroundResource(R.drawable.view_item_cartype_after);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_EB3131));
                        view.setFocusable(true);
                    } else {
                        view.setBackgroundResource(R.drawable.view_item_cartype_before);
                        ((TextView) view).setTextColor(getResources().getColor(R.color.color_666666));
                        view.setFocusable(false);
                    }
                }

            }
        };
        mAdapter2.setOnClickListener(new OnClickCommonListener() {
            @Override
            public void onClickListener(View view, int position) {
                switch (view.getId()) {
                    case R.id.content:
                        synchronized (lock) {
                            if (position < 0) {
                                return;
                            }
                            mCurClick = TYPE_CLICK_CARTYPE;
                            mCurSelectCarTypeItem = YSConstant.INVALID;
                            if (view.isFocusable()) {
                                Intent intent = new Intent();
                                intent.putExtra(RESULT_POSITION, position);
                                setResult(YSConstant.Activity_RESULT_OK, intent);
                                finish();
                            } else {
                                view.setFocusable(true);
                                view.setBackgroundResource(R.drawable.view_item_cartype_after);
                                ((TextView) view).setTextColor(getResources().getColor(R.color.color_EB3131));
                                for (int i = 0; i < mCurCarTypeList.size(); i++) {
                                    if (i != position) {
                                        mCurCarTypeList.get(i).setFlag(false);
                                    }
                                }
                                mCurCarTypeList.get(position).setFlag(true);
                                mCurSelectCarTypeItem = position;
                                mAdapter2.notifyDataSetChanged();
                                mAdapter1.notifyDataSetChanged();
                            }
                        }
                        break;

                }
            }
        });
        mAdapter1.isHasFooter(false);
        mAdapter2.isHasFooter(false);
        recyclerView1.setLayoutManager(gridLayoutManager);
        recyclerView2.setLayoutManager(linearLayoutManager);
        recyclerView1.setAdapter(mAdapter1);
        recyclerView2.setAdapter(mAdapter2);
    }

    static class Config {
        String key = "";
        String value = "";
        Boolean flag = false;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public Boolean getFlag() {
            return flag;
        }

        public void setFlag(Boolean flag) {
            this.flag = flag;
        }
    }
}
